package com.zbbt.sportslottery.ui.fragment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.google.gson.JsonObject;
import com.zbbt.sportslottery.R;
import com.zbbt.sportslottery.app.App;
import com.zbbt.sportslottery.app.Constant;
import com.zbbt.sportslottery.app.ServerConfig;
import com.zbbt.sportslottery.bean.ColumnBean;
import com.zbbt.sportslottery.bean.NewsProgarm;
import com.zbbt.sportslottery.db.DbManager;
import com.zbbt.sportslottery.net.TypeGsonHttpHandler;
import com.zbbt.sportslottery.net.ZbHttpClient;
import com.zbbt.sportslottery.ui.activity.ChannelActivity;
import com.zbbt.sportslottery.ui.activity.MainActivity;
import com.zbbt.sportslottery.ui.widget.slidingtab.PagerSlidingTabStrip;
import com.zbbt.sportslottery.util.KeyUtil;
import com.zbbt.sportslottery.util.LogUtil;
import com.zbbt.sportslottery.util.UmengUtil;

/**
 * @author kangle 首页初始化PagerSlidingTabStrip
 */
public class HomeFragment extends BaseMenuFragment {
	private PagerSlidingTabStrip tabs;
	private ViewPager pager;
	private MyPagerAdapter adapter;
	private int currentColor = 0x92ccff;
	private ImageView TabChannel;
	private ImageView new_Programa_img;

	public static List<ColumnBean> channelItems = new ArrayList<ColumnBean>();

	public HomeFragment() {}

	public static HomeFragment getInstance() {
		return new HomeFragment();
	}

	@Override
	protected void initView(LayoutInflater inflater) {
		mView = inflater.inflate(R.layout.fragment_home, null);
		new_Programa_img = (ImageView) findViewById(R.id.new_Programa_img);
		initDataProgramaId();
		tabs = (PagerSlidingTabStrip) findViewById(R.id.home_tabs);
		pager = (ViewPager) findViewById(R.id.pager);
		TabChannel = (ImageView) findViewById(R.id.channel_tab);
		adapter = new MyPagerAdapter(this.getChildFragmentManager());
		pager.setAdapter(adapter);
		final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
				.getDisplayMetrics());
		pager.setPageMargin(pageMargin);
		tabs.setViewPager(pager);
		tabs.setIndicatorColor(getResources().getColor(R.color.tab_color_indicator));
		tabs.setIndicatorHeight(6);
		tabs.setTextColor(getResources().getColor(R.color.tabs_color_text));
		tabs.setTextSize(getResources().getDimensionPixelSize(R.dimen.big_m));
		tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				String name = channelItems.get(position).getName();
				if (name.equals("热点")) {
					UmengUtil.onEvent(context, Constant.UMENG_NEWS_TABS_REDIAN);
				} else if (name.equals("竞彩")) {
					UmengUtil.onEvent(context, Constant.UMENG_NEWS_TABS_JINGCAI);
				} else if (name.equals("专家")) {
					UmengUtil.onEvent(context, Constant.UMENG_NEWS_TABS_ZHUANJIA);
				} else if (name.equals("技巧")) {
					UmengUtil.onEvent(context, Constant.UMENG_NEWS_TABS_JIQIAO);
				} else if (name.equals("数字")) {
					UmengUtil.onEvent(context, Constant.UMENG_NEWS_TABS_SHUZI);
				} else if (name.equals("玩法")) {
					UmengUtil.onEvent(context, Constant.UMENG_NEWS_TABS_WANFA);
				}else if (name.equals("星站")) {
					UmengUtil.onEvent(context, Constant.UMENG_NEWS_TABS_XINGZHAN);
				}else if (name.equals("公告")) {
					UmengUtil.onEvent(context, Constant.UMENG_NEWS_TABS_GONGGAO);
				}
			}

			@Override
			public void onPageScrolled(int position, float arg1, int arg2) {
				LogUtil.printD("positionqqqq", position+"");
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {}
		});
	}

	@Override
	protected void setListener() {
		TabChannel.setOnClickListener(this);
	}

	public void initDataProgramaId() {
		channelItems.clear();
		if (DbManager.getChannel().size() > 1) {
			for (int i = 0; i < DbManager.getChannel().size(); i++) {
				if (DbManager.getChannel().get(i).getColumnid() == 1) {
					channelItems.add(DbManager.getChannel().get(i));
				}
			}
			App.userChannelList.clear();
			App.userChannelList.addAll(DbManager.getChannel());

			if (App.newsList != null && App.newsList.size() > 0) {
				List<String> Dblist = new ArrayList<String>();
				// 本地存储的栏目id
				List<String> newlist = new ArrayList<String>();
				// 最新的栏目id
				for (int i = 0; i < DbManager.getChannel().size(); i++) {
					Dblist.add(DbManager.getChannel().get(i).getProgramaId() + "");
				}
				/**
				 * 判断是否有新栏目
				 */
				for (int j = 0; j < App.newsList.size(); j++) {
					newlist.add(App.newsList.get(j).getProgramaId() + "");
					if (!Dblist.contains(App.newsList.get(j).getProgramaId() + "")) {
						new_Programa_img.setVisibility(View.VISIBLE);
						App.userChannelList.add(new ColumnBean(App.newsList.get(j).getProgramaId(),
								App.newsList.get(j).getProgramaName(), 1, 2));
					}
				}
				/**
				 * 判断是否有过时的栏目
				 */
				for (int k = 0; k < Dblist.size(); k++) {
					if (!newlist.contains(Dblist.get(k))) {
						for (int m = 0; m < App.userChannelList.size(); m++) {
							if (Dblist.get(k).equals(App.userChannelList.get(m).getProgramaId() + "")) {
								App.userChannelList.remove(m);
								channelItems.clear();
								for (int i = 0; i < App.userChannelList.size(); i++) {
									if (App.userChannelList.get(i).getColumnid() == 1) {
										channelItems.add(App.userChannelList.get(i));
									}
								}
								DbManager.savaChannel(App.userChannelList);
							}
						}
					}
				}
			}
		} else {
			App.userChannelList.clear();
			if (DbManager.getProgarmList() != null && DbManager.getProgarmList().size() > 0) {
				for (int i = 0; i < DbManager.getProgarmList().size(); i++) {
					App.userChannelList.add(new ColumnBean(DbManager.getProgarmList().get(i).getProgramaId(),
							DbManager.getProgarmList().get(i).getProgramaName(), 0, 1));
				}
				DbManager.savaChannel(App.userChannelList);
			} else {
				App.userChannelList.add(new ColumnBean(1, "热点", 0, 1));
				App.userChannelList.add(new ColumnBean(2, "竞彩", 0, 1));
				App.userChannelList.add(new ColumnBean(3, "专家", 0, 1));
				App.userChannelList.add(new ColumnBean(4, "技巧", 0, 1));
			}

			for (int i = 0; i < App.userChannelList.size(); i++) {
				if (App.userChannelList.get(i).getColumnid() == 1) {
					channelItems.add(App.userChannelList.get(i));
				}
			}
		}
	}

	@Override
	protected void onClickEvent(View v) {
		switch (v.getId()) {
		case R.id.channel_tab:
			UmengUtil.onEvent(context, Constant.UMENG_NEWS_TABS_DINGZHI);
			goActivity(ChannelActivity.class);
			new_Programa_img.setVisibility(View.GONE);
			break;
		default:
			break;
		}
	}

	@SuppressLint("ResourceAsColor")
	@Override
	public void onResume() {
		super.onResume();
		if (MainActivity.newFragment instanceof HomeFragment && tv_right != null) {
			tv_right.setVisibility(View.VISIBLE);
			tv_right.setText("");
			tv_right.setBackgroundResource(R.drawable.kaijiang);
		}
		if (App.CHANNELRESULT == 2) {
			setChangelView();
			App.CHANNELRESULT = 1;
		}
	}

	private void setChangelView() {
		channelItems.clear();
		for (int i = 0; i < App.userChannelList.size(); i++) {
			if (App.userChannelList.get(i).getColumnid() == 1) {
				channelItems.add(App.userChannelList.get(i));
			}
		}
		adapter.notifyDataSetChanged();
		tabs.notifyDataSetChanged();
		DbManager.savaChannel(App.userChannelList);
	}

	@Override
	protected void onRightClick() {
		((MainActivity) getActivity()).changeFragment(KeyUtil.FRAGMENT_DRAW);
	}

	public class MyPagerAdapter extends FragmentStatePagerAdapter {

		public MyPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return channelItems.get(position).getName();
		}

		@Override
		public int getCount() {
			return channelItems.size();
		}

		@Override
		public Fragment getItem(int position) {
			return ChildHomeFragment.newInstance(position, channelItems.get(position).getProgramaId());
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			Fragment f = (Fragment) super.instantiateItem(container, position);
			return f;
		}

		@Override
		public int getItemPosition(Object object) {
			return PagerAdapter.POSITION_NONE;
		}

	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.INTENT_ACTION_CHANGE_CITY);
		context.registerReceiver(broadcastReceiver, filter);
	}

	protected void getProgarmList() {
		ZbHttpClient.postNewApi(ServerConfig.API_NEWS_PROGRAM_LIST, new JsonObject(),
				new TypeGsonHttpHandler<List<NewsProgarm>>() {

					@Override
					public void onSuccess(List<NewsProgarm> data) {
						if (data != null && data.size() > 0) {
							List<NewsProgarm> pList = data;
							App.userChannelList.clear();
							for (int i = 0; i < pList.size(); i++) {
								App.userChannelList.add(new ColumnBean(pList.get(i).getProgramaId(), pList
										.get(i).getProgramaName(), 0, 1));
							}
							setChangelView();
						} else {
							App.userChannelList.clear();
							App.userChannelList.add(new ColumnBean(1, "热点", 0, 1));
							App.userChannelList.add(new ColumnBean(2, "竞彩", 0, 1));
							App.userChannelList.add(new ColumnBean(3, "专家", 0, 1));
							App.userChannelList.add(new ColumnBean(4, "技巧", 0, 1));
							setChangelView();
						}
					}

					@Override
					public void onFailure(String errorCode, String errorMsg) {

					}

				});
	}

	/**
	 * 注册的广播
	 */
	private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (Constant.INTENT_ACTION_CHANGE_CITY.equals(intent.getAction())) {
				if (HomeFragment.channelItems != null && HomeFragment.channelItems.size() > 0) {
					DbManager.deleteNewsList(null);
				}
				getProgarmList();
			}
		}

	};
}
